package test01111;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

public class Client extends Application {
    private ObservableList<Contact> contacts;
    private ListView<Contact> contactListView;
    private TextField nameField;
    private TextField addressField;
    private TextField phoneField;
    private Button addButton;
    private Button deleteButton;
    private Button editButton;
    private Button saveButton;
    private Button cancelButton;

    private ObjectOutputStream outputStream;
    private ObjectInputStream inputStream;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        // 连接服务器
        try {
            Socket socket = new Socket("localhost", 8000);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            inputStream = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 初始化联系人列表
        contacts = FXCollections.observableArrayList();
        refreshContacts();

        // 创建UI元素
        contactListView = new ListView<>();
        contactListView.setItems(contacts);

        nameField = new TextField();
        addressField = new TextField();
        phoneField = new TextField();

        addButton = new Button("添加");
        deleteButton = new Button("删除");
        editButton = new Button("编辑");
        saveButton = new Button("保存");
        cancelButton = new Button("取消");

        // 设置按钮事件处理程序
        // 设置按钮事件处理程序
        addButton.setOnAction(e -> {
            String name = nameField.getText();
            String address = addressField.getText();
            String phone = phoneField.getText();

            if (name.isEmpty() || address.isEmpty() || phone.isEmpty()) {
                showAlert("请填写完整的联系人信息！");
                return;
            }

            Contact contact = new Contact(name, address, phone);
            contacts.add(contact);

            nameField.clear();
            addressField.clear();
            phoneField.clear();
        });

        deleteButton.setOnAction(e -> {
            Contact selectedContact = contactListView.getSelectionModel().getSelectedItem();
            if (selectedContact != null) {
                contacts.remove(selectedContact);
            }
        });

        editButton.setOnAction(e -> {
            Contact selectedContact = contactListView.getSelectionModel().getSelectedItem();
            if (selectedContact != null) {
                nameField.setText(selectedContact.getName());
                addressField.setText(selectedContact.getAddress());
                phoneField.setText(selectedContact.getPhone());
                addButton.setDisable(true);
                deleteButton.setDisable(true);
                editButton.setDisable(true);
                saveButton.setDisable(false);
                cancelButton.setDisable(false);
            }
        });

        saveButton.setOnAction(e -> {
            Contact selectedContact = contactListView.getSelectionModel().getSelectedItem();
            if (selectedContact != null) {
                String name = nameField.getText();
                String address = addressField.getText();
                String phone = phoneField.getText();

                if (name.isEmpty() || address.isEmpty() || phone.isEmpty()) {
                    showAlert("请填写完整的联系人信息！");
                    return;
                }

                selectedContact.setName(name);
                selectedContact.setAddress(address);
                selectedContact.setPhone(phone);

                nameField.clear();
                addressField.clear();
                phoneField.clear();

                addButton.setDisable(false);
                deleteButton.setDisable(false);
                editButton.setDisable(false);
                saveButton.setDisable(true);
                cancelButton.setDisable(true);
            }
        });

        cancelButton.setOnAction(e -> {
            nameField.clear();
            addressField.clear();
            phoneField.clear();

            addButton.setDisable(false);
            deleteButton.setDisable(false);
            editButton.setDisable(false);
            saveButton.setDisable(true);
            cancelButton.setDisable(true);
        });


        // 创建布局
        GridPane gridPane = new GridPane();
        gridPane.setPadding(new Insets(10));
        gridPane.setHgap(10);
        gridPane.setVgap(5);

        gridPane.add(new Label("姓名"), 0, 0);
        gridPane.add(nameField, 1, 0);
        gridPane.add(new Label("住址"), 0, 1);
        gridPane.add(addressField, 1, 1);
        gridPane.add(new Label("电话"), 0, 2);
        gridPane.add(phoneField, 1, 2);

        HBox hbox1 = new HBox(addButton, deleteButton, editButton);
        hbox1.setSpacing(10);

        HBox hbox2 = new HBox(saveButton, cancelButton);
        hbox2.setSpacing(10);

        VBox vbox1 = new VBox(hbox1, hbox2);
        vbox1.setPadding(new Insets(10));

        VBox vbox2 = new VBox(gridPane, vbox1);
        vbox2.setAlignment(Pos.TOP_CENTER);

        HBox hbox3 = new HBox(contactListView);
        hbox3.setPadding(new Insets(10));

        VBox vbox3 = new VBox(hbox3);
        vbox3.setAlignment(Pos.CENTER);

        HBox hbox4 = new HBox(vbox2, vbox3);
        hbox4.setSpacing(20);
        hbox4.setPadding(new Insets(10));

        // 创建场景并显示窗口
        Scene scene = new Scene(hbox4, 600, 400);
        stage.setScene(scene);
        stage.setTitle("个人通讯录");
        stage.show();
    }

    private void refreshContacts() {
        try {
            outputStream.writeUTF("list");
            outputStream.flush();

            List<Contact> newContacts = (List<Contact>) inputStream.readObject();
            contacts.clear();
            contacts.addAll(newContacts);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void addContact(Contact contact) {
        try {
            outputStream.writeUTF("add");
            outputStream.writeObject(contact);
            outputStream.flush();

            boolean success = inputStream.readBoolean();
            if (success) {
                refreshContacts();
            } else {
                showAlert("添加联系人失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void deleteContact(int index) {
        try {
            outputStream.writeUTF("delete");
            outputStream.writeInt(index);
            outputStream.flush();

            boolean success = inputStream.readBoolean();
            if (success) {
                refreshContacts();
            } else {
                showAlert("删除联系人失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateContact(int index, Contact contact) {
        try {
            outputStream.writeUTF("update");
            outputStream.writeInt(index);
            outputStream.writeObject(contact);
            outputStream.flush();

            boolean success = inputStream.readBoolean();
            if (success) {
                refreshContacts();
            } else {
                showAlert("更新联系人失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showAlert(String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
